<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :exclude-values="['userCName', 'userCName1', 'groupCname', 'groupCname1', 'endTime']"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      @submit="searchFn"
      @reset="resetFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="processDefKey" label="流程名称">
          <ProcessName v-model="state.query.processDefKey"></ProcessName>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="instStatus" label="流程状态">
          <FISelect v-model="state.query.instStatus" valueCustom="value" :options="processStatus" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="startTime" label="发起时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="date"
            placeholder="发起时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="date"
            placeholder="发起时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <!-- <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="endTime" label="至">
          <FIDatePicker
            value-format="YYYY-MM-DD"
            v-model="state.query.endTime"
            type="date"
            placeholder="发起时间"
            clearable
          />
        </FIFormItem>
      </el-col> -->
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="查询结果"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="processDefKey"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import ProcessName from '../../components/ProcessName.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import DeptTree from '../../components/DeptTree'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import {
  apiQueryVote,
  apiQueryDetails,
  apiExportDetails,
  apiQueryUser,
  apiQueryDept,
  apiQueryProcessesDef,
  apiQueryProcessEffi,
  apiBranDownload,
} from '@/api/modules/EW.js'
import { useRouter } from 'vue-router'
const route = useRoute()
const loadMoreEnd = ref(false)
const processPage = ref(1)
const searchWrapperSpan = 8
const router = useRouter()
const processArr = ref([])
const isTableLoading = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const userList = ref([])
const deptList = ref([])
const state = reactive({
  query: {
    startDeptId: '',
    processDefKey: '',
    endTime: '',
    startTime: '',
    instStatus: '',
    current: 1,
    size: 10,
    userCName: '',
    groupCname: '',
    groupCname1: '',
    userCName1: '',
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const processStatus = [
  {
    value: 'active',
    label: '正运行',
  },
  {
    value: 'suspend',
    label: '挂起',
  },
  {
    value: 'finish',
    label: '结束',
  },
  {
    value: 'manual-finish',
    label: '终止',
  },
]
const columns: Column[] = reactive([
  {
    label: '部门',
    prop: 'deptName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },

  {
    label: '流程名称',
    prop: 'processDefName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程数量',
    prop: 'processCount',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程状态',
    prop: 'instStatus',
    align: 'center',
    editType: 'select',
    editConfig: {
      options: [
        {
          value: 'active',
          label: '正运行',
        },
        {
          value: 'suspend',
          label: '挂起',
        },
        {
          value: 'finish',
          label: '结束',
        },
        {
          value: 'manual-finish',
          label: '终止',
        },
      ],
    },
  },
  {
    label: '全流程平均时效（单位：小时）',
    prop: 'maxTime',
    sortable: true,
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '',
    prop: 'action',
    actionConfig: [{ id: 'detail', type: 'top' }],
  },
])

const checkedRows = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const resetFn = () => {
  state.query.groupCname = ''
  // state.query.userCName = ''
  // state.query.categoryName = ''
  // state.query.productName = ''
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
//导出
const exportClick = () => {
  apiBranDownload(state.query)
}
//操作
const actionClick = (item, rowData, btnInfo) => {
  console.log(router, 'router')
  router.push({
    name: 'ProcInst',
    query: {
      deptId: rowData.deptId,
      processDefKey: rowData.processDefKey,
      instStatus: rowData.instStatus,
      startTime:state.query.startTime,
      endTime:state.query.endTime
    },
  })
}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns

  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  let par = {
    ...state.query,
    startTime: state.query.processStartTime ? state.query.processStartTime[0] : '',
    endTime: state.query.processStartTime ? state.query.processStartTime[1] : '',
  }
  delete par.processStartTime
  apiQueryProcessEffi(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const getBJlist = () => {
  apiQueryVote({ vote: '' })
    .then((res) => {
      if (res.data.success) {
        // saveSuccessful.value = true
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {})
}
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryAll = () => {
  let par = {
    current: processPage.value,
    size: 10,
  }
  apiQueryProcessesDef(par)
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        // processArr.value = res.data.data.result.map((v) => {
        //   return {
        //     label: `${v.processDefinitionKey} - ${v.processDefinitionName}`,
        //     value: v.processDefinitionKey,
        //   }
        // })
        processArr.value = processArr.value.concat(res.data.data.result)
        if (processPage.value * 10 >= res.data.data.count) {
          loadMoreEnd.value = true
        }
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  getBJlist() //获取表决数据
  getQueryAll() //查询流程名称
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  searchFn() //初始化不掉数据
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
